package com.zhang.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoadBananceImpl implements LoadBanance{
    //获取服务数
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    int next ;
    int current ;
    //访问服务数
    public final int getAndInstance(){
        do{
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : next+1;

        }while(!this.atomicInteger.compareAndSet(current,next));
        System.out.println("***第几次访问: "+ next);
        return next;

    }
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int index = getAndInstance() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
